
<template>
  <div>
    <h1>Create News</h1>
    <el-form label-width="120px">
      <el-form-item label="开始日期时间:">
        <el-date-picker
          v-model="startTime"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-for="(item, index) in timeUnits" :key="index" :label="item.label">
        <el-input-number v-model="item.value" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="countEndTime">结束时间</el-button>
        <el-button type="danger" @click="clearTime">清空时间</el-button>
      </el-form-item>
      <el-form-item v-if="endTime" label="结束日期时间:">
        <el-input v-model="endTime" readonly style="width: 200px"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      startTime: '',
      timeUnits: [
        { label: '年', value: 0 },
        { label: '月', value: 0 },
        { label: '日', value: 0 },
        { label: '时', value: 0 },
        { label: '分', value: 0 },
        { label: '秒', value: 0 }
      ],
      endTime: ''
    };
  },
  methods: {
    countEndTime() {
      if (!this.startTime) {
        this.$message.error('请选择开始日期时间');
        return;
      }
      let startDate = new Date(this.startTime);
      startDate.setFullYear(startDate.getFullYear() + parseInt(this.timeUnits[0].value));
      startDate.setMonth(startDate.getMonth() + parseInt(this.timeUnits[1].value));
      startDate.setDate(startDate.getDate() + parseInt(this.timeUnits[2].value));
      startDate.setHours(startDate.getHours() + parseInt(this.timeUnits[3].value));
      startDate.setMinutes(startDate.getMinutes() + parseInt(this.timeUnits[4].value));
      startDate.setSeconds(startDate.getSeconds() + parseInt(this.timeUnits[5].value));
      this.endTime = startDate.toLocaleString();
    },
    clearTime() {
      this.startTime = '';
      this.timeUnits.forEach(item => {
        item.value = 0;
      });
      this.endTime = '';
    }
  }
};
</script>

<style>

</style>
